<template>
  <div class="dashboard-container">
    <!-- 搜索栏 -->
    <div class="search">
      <el-form ref="form" :model="params" label-position="top" size="medium">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="名称">
              <el-input placeholder="请输入名称" v-model="params.name" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="对象类型">
              <el-select filterable clearable v-model="params.objectType" placeholder="请选择" style="width: 100%;">
                <el-option v-for="item, index in objectList" :key="index" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="资产类型">
              <el-select filterable clearable v-model="params.propertyType" placeholder="请选择" style="width: 100%;">
                <el-option v-for="item, index in TARGET_TYPE_LIST" :key="index" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="公司业务类型">
              <el-select filterable clearable v-model="params.customerCompanyBusinessEiid" placeholder="请选择"
                style="width: 100%;">
                <el-option v-for="item, index in ustomerCompanyBusinessEiidList" :key="index" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="公司">
              <el-cascader clearable style="width: 100%;" v-model="customerCompanyId" :options="companyList">
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="opt">
      <el-button type="primary" @click="handleAdd('create')">
        <i class="el-icon-plus"></i>
        创建
      </el-button>
      <el-button type="primary" plain @click="handleSearch">
        <i class="el-icon-search"></i>
        查询
      </el-button>

    </div>

    <!-- 列表 -->
    <el-table :data="list">
      <el-table-column label="模板名称" prop="name"></el-table-column>
      <el-table-column label="对象类型" prop="objectTypeName"></el-table-column>
      <el-table-column label="资产类型" prop="propertyTypesName"></el-table-column>
      <el-table-column label="创建时间" prop="createTime"></el-table-column>

      <el-table-column label="操作">
        <template slot-scope="{row}">
          <el-button type="text" @click="handleAdd('update', row)">编辑</el-button>
          <el-button type="text" style="color: red;" @click="handleDelete(row.id)">删除</el-button>
          <el-button type="text" v-if="row.fileUrl"><a
              :href="`javascript:POBrowser.openWindow('${API_BASE_URL}/pageOffice/openOSSFile?filePath=${row.fileUrl}&editFlag=1&fileTitle='+ encodeURIComponent('报告模板'), 'width=1200px;height=900px;');`">打开报告模板</a></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="page">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="params.pageIndex + 1" :page-sizes="[10, 20, 30, 40]" :page-size="params.pageCount"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 新增\编辑 -->
    <el-dialog :title="dialogType == 'create' ? '新增模板' : '编辑模板'" :visible.sync="dialogVisible" :close-on-click-modal="false"
      @close="dialogVisible = false" width="800px">
      <el-form ref="form" :rules="rules" :model="temp" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input placeholder="请输入名称" v-model="temp.name"></el-input>
        </el-form-item>
        <el-form-item label="对象类型" prop="objectType">
          <el-select  v-model="temp.objectType" placeholder="请选择" style="width: 100%;" :disabled="dialogType=='update'" @change="handleChangeObject">
            <el-option v-for="item, index in objectList" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资产类型" prop="propertyTypes" v-if="temp.objectType==8" >
          <el-select filterable clearable v-model="temp.propertyTypes" placeholder="请选择" style="width: 100%;" multiple>
            <el-option v-for="item, index in TARGET_TYPE_LIST" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模板类型" prop="templateType">
          <el-select @change="clearFile" filterable clearable v-model="temp.templateType" placeholder="请选择" style="width: 100%;" :disabled="temp.objectType==8||dialogType=='update'">
            <el-option v-for="item, index in TEMPLATE_TYPE_LIST" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报告类型" prop="reportTypes" v-if="temp.templateType==2">
          <el-select filterable clearable v-model="temp.reportTypes" placeholder="请选择" style="width: 100%;" multiple>
            <el-option v-for="item, index in REPORT_TYPES_LIST" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="公司" prop="customerCompanyIds">
          <el-cascader style="width: 100%;" v-model="temp.customerCompanyIds" :options="companyList"
            :props="{ multiple: true }">
          </el-cascader>
        </el-form-item>
        <el-form-item label="公司业务类型" prop="customerCompanyBusinessEiids">
          <el-select filterable v-model="temp.customerCompanyBusinessEiids" placeholder="请选择"
            style="width: 100%;" multiple>
            <el-option v-for="item, index in ustomerCompanyBusinessEiidList" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input placeholder="请输入描述" v-model="temp.description"></el-input>
        </el-form-item>
        <el-form-item label="排序值" prop="sortValue">
          <el-input placeholder="请输入排序值" v-model="temp.sortValue"></el-input>
        </el-form-item>
        
        
        <el-form-item label="模板：" prop="fileUrl">
          <span v-if="temp.fileUrl " style="margin-right: 10px;cursor: pointer;"
            @click="downloadFile(temp.fileUrl, temp.fileName )">
            {{ temp.fileName }}
          </span>
          <el-upload class="upload-demo" :action="OSS_CONFIG.host"
            :before-upload="(file) => hanldeUpload(file, 'fileName')"
            :on-success="() => handleAvatarSuccess('fileUrl')" :data="uploadData" :show-file-list="false">

            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit('form')">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import { fieldAsyncRefreshTemplateFields } from '@/api/field'
import { reportTemplateGetList, reportTemplateUpdate, reportTemplateCreate, reportTemplateDelete } from '@/api/reportTemplate'
import { OBJECT_ALL_TYPE_LIST, API_BASE_URL, TARGET_TYPE_LIST, OSS_BASE_URL, REPORT_TYPES_LIST, TEMPLATE_TYPE_LIST } from '@/utils/common'
import { companyGetTree } from '@/api/company'
import { transfromData, downloadFile } from '@/utils/tools'
import { enumInfo } from '@/api/enum'
import { commonGetUploadFilePolicy } from '@/api/common'
import moment from 'moment'

export default {
  name: 'Template',
  data() {
    return {
      OSS_BASE_URL,
      API_BASE_URL,
      api_url: '',
      OBJECT_ALL_TYPE_LIST,
      TARGET_TYPE_LIST,
      REPORT_TYPES_LIST,
      TEMPLATE_TYPE_LIST,
      list: [],
      total: 0,
      params: {
        customerCompanyBusinessEiid: '',
        customerCompanyId: '',
        enabled: '',
        name: '',
        objectType: '',
        pageCount: 10,
        pageIndex: 0,
        propertyType: '',
        reportType: '',
        templateType: ''
      },
      customerCompanyId: [],
      ustomerCompanyBusinessEiidList: [],
      companyList: [],
      dialogType: 'create',
      dialogVisible: false,
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        templateType: [{ required: true, message: '请选择模板类型', trigger: 'blur' }],
        reportTypes: [{ required: true, message: '请选择报告类型', trigger: 'blur' }],
        objectType : [{ required: true, message: '请选择对象类型', trigger: 'blur' }],
        fileUrl : [{ required: true, message: '请上传模板', trigger: 'blur' }],
      },
      temp: {},
      OSS_CONFIG: {
        accessid: '',
        dir: '',
        expire: '',
        host: '',
        policy: '',
        signature: ''
      },
      uploadData: {},
      objectList: [
        { label: '报告', value: 7 },
        { label: '评估对象', value: 8 },
      ]
    }
  },
  async mounted() {


    //获取公司列表
    let data = await companyGetTree({ userType: 2 })
    //默认最高5级
    this.companyList = this.treeTransForm(data)

    //获取业务列表
    let yewuType = await enumInfo({ id: 36 })
    this.ustomerCompanyBusinessEiidList = yewuType.items.filter(item => item.selectFlag == 1).map(item => {
      let name = item.name;
      let nowItem = JSON.parse(JSON.stringify(item));
      for (let i = 1; i < item.level; i++) {
        let parent = yewuType.items.filter(aItem => aItem.id == nowItem.parentId);
        if (parent.length > 0) {
          name = parent[0].name + '-' + name
        }
        nowItem = parent;
      }
      return { label: name, value: item.id }
    })

    this.getData();
    this.getOssConfig();
  },
  methods: {
    //修改模板类型，则清空上传的模板
    clearFile(){
      this.temp.fileUrl = '';
      this.temp.fileName = '';
    },
    //修改对象类型时候，做一下特殊判断，报告类型只能是文档模板
    handleChangeObject(e){
      console.log(e)
      if(e==7){
        //报告类型只能是文档模板
        this.temp.templateType = 1
      }
    },
    downloadFile(url, name) {
      downloadFile(url, name);
    },
    //点击删除模板
    handleDelete(id) {
      this.$confirm('此操作将永久删除该模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await reportTemplateDelete({ ids: [id] })
        this.getData();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //文件上传成功
    handleAvatarSuccess(name) {
      this.temp[name] = this.uploadData.key
    },
    //删除钩子
    handleRemove(file) {
      // this.temp.files = this.temp.files.filter(item=>{
      //   return item.indexOf(file.uid)==-1
      // })
    },
    //图片上传前，签名处理
    hanldeUpload(file, type) {
      console.log(file, type)
      if(this.temp.templateType==1&&!file.name.endsWith('xlsx')){
        //数据类型，判断文件类型为docx后缀
        this.$message.error({ message: '数据模板必须是xlsx文件' })
        return false
      }
      if(this.temp.templateType==2&&!file.name.endsWith('docx')){
        //数据类型，判断文件类型为docx后缀
        this.$message.error({ message: '文档模板必须是docx文件' })
        return false
      }
      this.temp[type] = file.name;
      let fileName = file.uid + '.' + file.name.split('.')[1]
      this.uploadData.name = fileName
      this.uploadData.key = this.OSS_CONFIG.dir + fileName
    },
    //获取Oss详情
    async getOssConfig() {
      let data = await commonGetUploadFilePolicy();
      this.OSS_CONFIG = data;
      this.uploadData = {
        policy: data.policy,
        OSSAccessKeyId: data.accessid,
        success_action_status: '200',
        signature: data.signature,
        key: data.dir,
        name: ''
      }
    },
    //提交表单
    submit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let temp = JSON.parse(JSON.stringify(this.temp))
          if (temp.customerCompanyIds.length > 0) {
            temp.customerCompanyIds = temp.customerCompanyIds.map(item => item[item.length - 1])
          }
          if (this.dialogType == 'create') {
            await reportTemplateCreate(temp)
            this.$message.success('创建成功')
          } else {
            await reportTemplateUpdate(temp)
            this.$message.success('修改成功')
          }
          this.handleSearch();
          this.dialogVisible = false;
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 点击新增编辑
    handleAdd(type, row) {
      this.dialogType = type;
      this.dialogVisible = true;
      if (type == 'create') {
        this.temp = {
          customerCompanyBusinessEiids: [],
          objectType: 7,
          templateType: 1,
          customerCompanyIds: [],
          description: '',
          name: '',
          fileUrl: '',
          fileName: '',
          methodTypeEiids: '',
          propertyTypes: [],
          sortValue: ''
        }
      } else {
        this.temp = row
      }

    },
    //树结构数据转化
    treeTransForm(arr) {
      return arr.map(item => {
        let children = null;
        if (item.companies.length > 0) {
          children = this.treeTransForm(item.companies)
        }
        return { label: item.name, value: item.id, children }
      })
    },
    //获取客户公司业务类型列表
    async getEiidList() {

    },
    // 初始化搜索
    handleSearch() {
      this.params.pageIndex = 0;
      this.getData();
    },
    // 同步字段
    async refresh(row) {
      let params = {
        objectType: row.objectType,
      }
      if (row.propertyType) {
        params.propertyType = row.propertyType
      }
      await fieldAsyncRefreshTemplateFields(params)
      this.$message.success({ message: '刷新成功' })
    },

    //获取数据
    async getData() {
      if (this.customerCompanyId.length > 0) {
        this.params.customerCompanyId = this.customerCompanyId[this.customerCompanyId.length - 1]
      }

      let data = await reportTemplateGetList(this.params)
      this.list = data.list.map(item => {
        item.propertyTypes = item.propertyTypes? item.propertyTypes.split(',').map(item => Number(item)): [];
        item.reportTypes = item.reportTypes?item.reportTypes.split(',').map(item => Number(item)): [];
        item.customerCompanyBusinessEiids = item.customerCompanyBusinessEiids?item.customerCompanyBusinessEiids.split(',').map(item => Number(item)):[]
        item.propertyTypesName = item.propertyTypes ? item.propertyTypes.map(item => {
          return transfromData(TARGET_TYPE_LIST, item);
        }).join(','):"";

        item.objectTypeName = transfromData(this.objectList,item.objectType)

        item.customerCompanyIds = item.customerCompanyIds.split(',').map(item => {
          let arr = [];
          this.companyList.forEach(comItem => {
            //默认公司只有三级，多级后面再说
            if (comItem.value == item) {
              arr.push(item)
            }
            if (comItem.children) {
              comItem.children.forEach(childItem => {
                if (childItem.value == item) {
                  arr.push(comItem.value)
                  arr.push(item)
                }
                if (childItem.children) {
                  childItem.children.forEach(thirdItem => {
                    if (thirdItem.value == item) {
                      arr.push(comItem.value)
                      arr.push(childItem.value)
                      arr.push(item)
                    }
                  })
                }
              })
            }

          })
          return arr;
        })
        item.createTime = moment(item.createTime).format('YYYY-MM-DD HH:mm:ss')
        return item;
      })
      this.total = data.totalCount
    },

    // 修改每页数量
    handleSizeChange(val) {
      this.params.pageIndex = 0;
      this.params.pageCount = val;
      this.getData();
    },
    // 切换分页
    handleCurrentChange(val) {
      this.params.pageIndex = val - 1;
      this.getData();
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
    position: relative;

    .opt {
      margin-bottom: 10px;
    }

    .page {
      padding: 20px 0;
      text-align: center;
    }
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
</style>